package antoine.ear.exo.recoaccords;

import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.Sequence;
import javax.sound.midi.Track;

import antoine.ear.GUI;
import antoine.ear.exo.Exo;
import antoine.ear.generator.ChordGenerator;
import antoine.ear.generator.NoteGenerator;
import antoine.ear.generator.SequenceGenerator;
import antoine.ear.generator.chords.Dom7Generator;
import antoine.ear.generator.chords.Maj7Generator;
import antoine.ear.generator.chords.Min7Generator;

public class RecoBass  extends Exo {
	
	public RecoBass(int tempo, int octave) {
		super(tempo, octave);
	}
	
	public String getPrintableResult() {
		return soluce;
	}

	public void generate() throws Exception {
		try {
			GUI gui = GUI.getInstance();
			Sequence seq = new Sequence(Sequence.PPQ, 1);
			Track track = seq.createTrack();
						
			Random random = new Random();
			int note = 36+random.nextInt(12);
			indication = NoteGenerator.getNoteName(note);
			
			track.add(createNoteOnEvent(note, 0));
			track.add(createNoteOffEvent(note, 1));
			track.add(createMetaMessOnEvent(note, 0, ACTIVATENOTE));
            track.add(createMetaMessOnEvent(note, 1, DESACTIVATENOTE));
			
            int ind = random.nextInt(gui.selectedChords.size());
			ChordGenerator gene = (ChordGenerator)gui.selectedChords.toArray()[ind];
			
			List l = gene.generate(note%12, 0 , 2);
			Iterator ite = l.iterator();
			while (ite.hasNext()){
				track.add((MidiEvent) ite.next());
			}
			l = gene.generate(note%12, 2, 2);
			ite = l.iterator();
			while (ite.hasNext()){
				track.add((MidiEvent) ite.next());
			}
			
			// Add new bass to track
			SequenceGenerator seqgene = gene.sequenceGenerator;
			seqgene.tickOffset = 0;
			l = seqgene.generate(1, note%12, 2);
			ite = l.iterator();
			while (ite.hasNext()){
				track.add((MidiEvent) ite.next());
			}			
            
			this.setSequence(seq);
			setTempo(tempo);
		} catch (InvalidMidiDataException e) {
			throw new Exception(e); 
		}
	}

	public String getIndication() {
		return "La basse est " + indication;
	}
}
